import { useState, useEffect } from 'react';
import np from '@/utils/numberPrecision';
import type { MutableRefObject } from 'react';

type TbaleHeightObj = {
  tableHeight: number;
  headerHeight: number;
  containerHeight: number;
  updateHeight: () => void;
};

function useAntdTableScroll(
  target: MutableRefObject<HTMLElement | undefined | null>,
): TbaleHeightObj {
  const [tableHeight, setTableHeight] = useState<number>(0);
  const [headerHeight, setHeaderHeight] = useState<number>(0);
  const [containerHeight, setContainerHeight] = useState<number>(0);

  const updateHeight = () => {
    if (target.current) {
      setContainerHeight(target.current.clientHeight);
      const header = target.current.querySelector('.ant-table-header') as HTMLElement;
      if (header) {
        setHeaderHeight(header.clientHeight);
      }
    }
  };

  useEffect(() => {
    if (containerHeight > 0 && containerHeight > 0) {
      setTableHeight(np.minus(containerHeight, headerHeight));
    }
  }, [headerHeight, containerHeight]);

  useEffect(() => {
    updateHeight();
    window.addEventListener('resize', updateHeight);

    return () => {
      window.removeEventListener('resize', updateHeight);
    };
  }, [target]);

  return {
    tableHeight,
    headerHeight,
    containerHeight,
    updateHeight,
  };
}

export { useAntdTableScroll };
